package com.trump.baiduim.controller;

import com.alibaba.fastjson.JSONObject;
import com.trump.baiduim.model.User;
import com.trump.baiduim.service.UserService;
import com.trump.baiduim.utils.EncryptUtil;
import com.trump.baiduim.utils.ErrorCode;
import com.trump.baiduim.utils.ResultUtil;
import com.trump.baiduim.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xujb
 * @date 2020/11/24 13:59
 */
@RestController
@Slf4j
@RequestMapping("/api/user")
public class UserController {
	/**
	 * token
	 */
	private String token = "";
	@Autowired
	private UserService userService;
	@Autowired
	private ResultUtil resultUtil;
	@Autowired
	private EncryptUtil encryptUtil;
	@Autowired
	private TokenUtil tokenUtil;


	@PostMapping("/register")
	public ResultUtil register(@RequestBody Map<String,String> object) throws Exception {
		try {
			//查询要注册的用户是否存在
			User user = userService.queryUsernameIsExist(object.get("userAccount"));
			if(user!=null){
				return resultUtil.ofFail(500,"该账号已存在，请登录");
			}else{
				//加入密码
				User registuser = JSONObject.parseObject(JSONObject.toJSONString(object),User.class);
				registuser.setUserPassword(encryptUtil.encryptPassword(object.get("userPassword")));
				registuser.setUserSalt(encryptUtil.generateSalt());

				userService.registerUser(registuser);
				return resultUtil.ofSuccess();
			}
		} catch (Exception e) {
			log.error("register调用失败",e);
			return null;
		}
	}
	@PostMapping("/updateInfo")
	public ResultUtil updataInfo(@RequestBody Map<String,String> object) {

		try {
			token = object.get(token);
			if (tokenUtil.verify(token)) {
				User user = JSONObject.parseObject(JSONObject.toJSONString(object),User.class);
				userService.updataInfo(user);
				return resultUtil.ofSuccess();
			} else {
				return resultUtil.ofFail(500,"没经过授权，请重新登陆");
			}
		} catch (Exception e) {
			log.error("register调用失败",e);
			return null;
		}

	}
	@PostMapping("/signOut")
	public ResultUtil signOut(HttpServletRequest request, HttpServletResponse response ) {

		return null;

	}

	/**
	 * ************************************
	 */

	/**
	 *
	 * 用户登陆功能
	 *
	 * @param map
	 * @return
	 */
	@PostMapping("/login")
	public ResultUtil login(@RequestBody Map<String,String> map){

		String userAccount = map.get("userAccount");
		String userPassword = map.get("userPassword");

		//1.判断用户账号和密码不能为空
		if(userAccount == null || "".equals(userAccount)){
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"用户账号不能为空！！！");
		}else if(userPassword == null || userPassword.equals("")){
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"用户密码不能为空！！！");
		}

		//2.判断用户是否存在
		String encryptedPassword = null;
		try {
			encryptedPassword = encryptUtil.encryptPassword(userPassword);
		} catch (Exception e) {
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"密码加密出错！！！");
		}
		User user = userService.findUserByUserAccountAndPassword(userAccount,encryptedPassword);
		if(user == null || "".equals(user)){
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"用户名不存在或密码错误或已在另一台设备登陆！！！");
		}
		userService.updateUserStatus(userAccount);
		//3. 用户登陆成功

		//生成用户的token
		String token = tokenUtil.token(userAccount,userPassword);
		ResultUtil resultUtilOfSuccess= resultUtil.ofSuccess(user);
		resultUtilOfSuccess.setMsg("登录成功！！！");
		resultUtilOfSuccess.setToken(token);
		return resultUtilOfSuccess;
	}

	/**
	 * 上传用户头像
	 * @param file
	 * @param userAccount
	 * @param token
	 * @return
	 */
	@PostMapping("/upload")
	public ResultUtil uploadUserHeadPortrait(MultipartFile file, String userAccount, String token) throws ParseException {

		//判断用户是否登录
		if(userAccount == null || "".equals(userAccount)){
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"用户账号为空！！！");
		}

		//验证token
		if(token == null || "".equals(token)){
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"token为空！！！");
		}else if(!tokenUtil.verify(token)) {
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"token验证失败！！！");
		}

		// 首先校验图片格式
		String[] imageType = {"jpg","jpeg", "png", "bmp", "gif"};
		List<String> imageList = new ArrayList<>(imageType.length);
		Collections.addAll(imageList,imageType);
		// 获取文件名，带后缀
		String originalFilename = file.getOriginalFilename();
		// 获取文件的后缀格式
		String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
		//判断图像后缀类型是否正确
		if(!imageList.contains(fileSuffix)){
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"请上传正确类型头像！！！");
		}
		//新的文件名字
		String newFileName = UUID.randomUUID() + "_" + originalFilename;
		//该方法返回的为当前项目的工作目录，即在哪个地方启动的java线程
		String dirPath = System.getProperty("user.dir");
		//新的路径
		String path = File.separator + "uploadImg" + File.separator + userAccount
				+ File.separator + newFileName;
		//封装上传文件位置的全路径
		File targetFile = new File(dirPath, path);
		if(!targetFile.getParentFile().exists()){
			targetFile.getParentFile().mkdirs();
		}
		try {
			//把头像上传到封装好的指定路径上
			file.transferTo(targetFile);
		} catch (IOException e) {
			return resultUtil.ofFail(ErrorCode.EXCEPTION.getCode(),"图像上传本地失败！！！");
		}
		String finalPath = dirPath + path;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
		String currentTime = simpleDateFormat.format(System.currentTimeMillis());
		Date updateTime = simpleDateFormat.parse(currentTime);
		//保存上传的头像地址到数据库
		userService.uploadUserHeadPortrait(userAccount,finalPath,updateTime);
		return resultUtil.ofSuccess();
	}

}
